<template>
  <div class="add">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品编码" prop="item_code">
        <el-input v-model="ruleForm.item_code" placeholder="非必填"></el-input>
      </el-form-item>
      <el-form-item label="货架编号" prop="repertory">
        <el-input v-model="ruleForm.repertory" placeholder='编号、层号、单元号，以"-"分隔'></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.stop="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import DB from '../axios/db'
export default {
  name: 'add',
  data () {
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('商品名称不能为空'))
      } else {
        callback()
      }
    }
    // let validateCode = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('商品编码不能为空'))
    //   } else {
    //     callback()
    //   }
    // }
    let validateRepertory = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('货架编号不能为空'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        name: '',
        item_code: '',
        repertory: ''
      },
      rules: {
        name: [{ validator: validateName, trigger: 'blur' }],
        // item_code: [{ validator: validateCode, trigger: 'blur' }],
        repertory: [{ validator: validateRepertory, trigger: 'blur' }]
      }
    }
  },
  created () {
    this.$Variable.userLogin()
  },
  methods: {
    submitForm (formName) {
      const _this = this
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(_this.ruleForm, '校验通过')
          DB.addTool(_this.ruleForm).then(res => {
            // console.log(res)
            if (res.code === 0) {
              _this.$message({
                message: res.message || '添加成功',
                type: 'success'
              })
            } else {
              _this.$message({
                message: res.message || '添加失败',
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
.add {
}
</style>
